﻿/*----------------------------------------------------------------
//  <copyright file="SequenceSlaveDatabaseSelector.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2023-12-06 10:02</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Entity
{
    #region "顺序轮询从数据库选择器"
    /// <summary>
    /// 顺序轮询从数据库选择器
    /// </summary>
    public sealed class SequenceSlaveDatabaseSelector : ISlaveDatabaseSelector
    {
        //字段
        private static readonly object LockObj = new();
        private int _sequenceIndex;
        private readonly ILogger _logger;

        #region "属性"
        #region "获取 名称"
        /// <summary>
        /// 获取 名称
        /// </summary>
        public string Name => "Sequence";
        #endregion
        #region "获取 从数据库选择策略"
        /// <summary>
        /// 获取 从数据库选择策略
        /// </summary>
        public SlaveDatabaseSelectorType SelectorType => SlaveDatabaseSelectorType.Sequence;
        #endregion

        #endregion

        #region "构造函数"
        #region "初始化一个 <see cref="SequenceSlaveDatabaseSelector"/> 类型的新实例"
        /// <summary>
        /// 初始化一个 <see cref="SequenceSlaveDatabaseSelector"/> 类型的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public SequenceSlaveDatabaseSelector(IServiceProvider provider)
        {
            _logger = provider.GetLogger(GetType());
        }
        #endregion

        #endregion

        #region "方法"
        #region "从所有从数据库中返回一个"
        /// <summary>
        /// 从所有从数据库中返回一个
        /// </summary>
        /// <param name="slaves">所有从数据库</param>
        /// <returns></returns>
        public SlaveDatabaseInfo Select(SlaveDatabaseInfo[] slaves)
        {
            lock (LockObj)
            {
                if (_sequenceIndex > slaves.Length - 1)
                {
                    _sequenceIndex = 0;
                }

                SlaveDatabaseInfo slave = slaves[_sequenceIndex];

                _logger.LogDebug("顺序选取了 {name} 从数据库，顺序号：{sequenceIndex}。", slave.Name, _sequenceIndex);

                _sequenceIndex++;
                return slave;
            }
        }
        #endregion

        #endregion

    }
    #endregion

}
